package com.atguigu.gulimall.ssoserver.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * @author: xuesm
 * @date: 2025/2/8 15:03
 */
@Controller
public class LoginController {

    @Autowired
    private StringRedisTemplate redisTemplate;


    @GetMapping("/login.html")
    public String loginPage(@RequestParam(value = "redirect_url", required = false) String url, Model model,
                            @CookieValue(value = "sso_token", required = false) String sso_token){
        if (!StringUtils.isEmpty(sso_token)){
            // 说明之前有人登录过
            return "redirect:" + url + "?token=" + sso_token;
        }
        model.addAttribute("url", url);
        return "login";
    }

    @ResponseBody
    @GetMapping("/userInfo")
    public String userInfo(@RequestParam(value = "token", required = false) String token){
        String username = redisTemplate.opsForValue().get(token);
        return username;
    }

    @PostMapping("/doLogin")
    public String login(@RequestParam("username") String username,
                        @RequestParam("password") String password,
                        @RequestParam("url") String url,
                        HttpServletResponse response){
        if (!StringUtils.isEmpty(username) && !StringUtils.isEmpty(password)){
            String uuid = UUID.randomUUID().toString().replace("-", "");
            redisTemplate.opsForValue().set(uuid, username);

            Cookie cookie = new Cookie("sso_token", uuid);
            response.addCookie(cookie);
            if (!StringUtils.isEmpty(url)){
                return "index";
            }
            // 登录成功跳转，回到之前的页面
            return "redirect:" + url + "?token=" + uuid;
        }
        // 登录失败，跳回首页
        return "login";
    }
}
